<?php 
/** 
 * 左旋转字符串
 * 对于一个给定的字符序列S，请你把其循环左移K位后的序列输出。例如，字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果，即“XYZdefabc”
 * 解答：先将从0开始到K位的字符串逆转，再将K位到末尾的字符串逆转，最后将整个字符串逆转
 */

function LeftRotateString($str, $n)
{
    if (!$str) {
    	return '';
    }
    if ($n <= 0) {
    	return $str;
    }

    $firStr = substr($str, 0, $n);
    $endStr = substr($str, $n);
    $firStr = reserve($firStr);
    $endStr = reserve($endStr);
    $retStr = reserve($firStr.$endStr);
    var_dump($retStr);
}


function reserve($str)
{
	$left = 0;
	$right = strlen($str) - 1;
	while($left < $right) {
		$temp = $str[$left];
		$str[$left] = $str[$right];
		$str[$right] = $temp;
		$left++;
		$right--;
	}
	return $str;
}

$str = 'adcdefg';
LeftRotateString($str, 3);